from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import pytest


test_cases = [("standard_user","secret_sauce","success",None),
              ("locked_out_user","secret_sauce","failure","Epic sadface: Sorry, this user has been locked out."),
              ("problem_user","secret_sauce","success",None),
              ("problem_user","123456","failure","Epic sadface: Username and password do not match any user in this service"),
              ("","secret_sauce","failure","Epic sadface: Username is required"),
              ("error_user","","failure","Epic sadface: Password is required")]
@pytest.mark.parametrize("username,password,expected,error_messenger",test_cases,ids=[case[2] for case in test_cases])
def test_login(username,password,expected,error_messenger,_):
    driver = None
    try:
        driver = webdriver.Chrome()  # 第一步：创建浏览器窗口对象
        driver.get("https://www.saucedemo.com/")  # 第二步：获取链接，get链接
        wait = WebDriverWait(driver, 10)
        wait.until(EC.title_contains("Swag Labs")) # 测试页面是否正常打开
        print("页面标题验证成功")
        username_field = wait.until(EC.element_to_be_clickable((By.ID,"user-name")))
        # 测试登陆操作用例是否正常执行
        username_field.clear()
        username_field.send_keys(username)
        password_field = wait.until(EC.element_to_be_clickable((By.ID,"password")))
        password_field.clear()
        password_field.send_keys(password)
        login_button = wait.until(EC.element_to_be_clickable((By.ID,"login-button")))
        login_button.click()
        if expected == "success":
            # 验证登陆成功
            wait.until(EC.url_contains('/inventory.html'))
            products_bool =  wait.until(EC.text_to_be_present_in_element((By.CLASS_NAME,'title'),"Products"))
            assert products_bool is True
        else:
            current_url = driver.current_url
            assert current_url == "https://www.saucedemo.com/"
            error_element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME,"error-message-container")))
            actual_error_msg = error_element.text.strip()
            assert actual_error_msg == error_messenger,\
                f"错误提示不匹配！预期：{error_messenger},实际:{actual_error_msg}"
            print(f"登陆失败（符合预期）：账号：{username},密码：{password},错误提示{error_messenger}")
        time.sleep(2)

    except Exception as e:
        print(f"测试失败{e}")
    finally:
        driver.quit()



if __name__ == "__main__":
    pytest.main(["-v", __file__])  # 使用pytest方式运行所有用例
